#-*- encoding:utf-8 -*-

from django.contrib.auth.models import AbstractUser
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

from django.utils import timezone


class OrgStructure(MPTTModel):
    """
    组织机构表
    """
    department_id = models.IntegerField(verbose_name='部门id', null=True, blank=True)
    name = models.CharField(verbose_name='名称', max_length=50)
    parent = TreeForeignKey('self', verbose_name='上级机构',
                            on_delete=models.PROTECT,
                            null=True, blank=True, related_name='children')
    # 机构权重 +　个人权重　＝　100%
    org_ratio = models.PositiveSmallIntegerField(verbose_name='机构权重', default=50)
    managers = models.ManyToManyField('User', verbose_name='负责人',
                                      related_name='manager_org', blank=True)
    created_time = models.DateTimeField(verbose_name='创建时间',
                                        default=timezone.now)
    updated_time = models.DateTimeField(verbose_name="更新时间", auto_now=True, blank=True)
    is_active = models.BooleanField(default=True, verbose_name="是否激活状态")

    class Meta:
        verbose_name = '组织机构'
        verbose_name_plural = verbose_name

    class MPTTMeta:
        order_insertion_by = ['name']

    def is_parent_manager(self, user):
        """
        判断用户是否为当前机构的上级负责人
        """
        parent_orgs = self.get_ancestors()
        manager_orgs = user.manager_org.all()
        if set(manager_orgs) & set(parent_orgs):
            return True
        return False

    def __str__(self):
        return self.name if self.is_root_node() else '{}-{}'.format(
            self.parent, self.name)

    def get_full_name(self):
        return str(self)


class User(AbstractUser):
    """
    用户表
    """
    nickname = models.CharField(max_length=50, verbose_name="姓名昵称", default="匿名")
    mobile = models.CharField(max_length=11, verbose_name="手机号码", null=True, blank=True)
    avatar = models.CharField(max_length=200, verbose_name='头像链接', null=True, blank=True)
    org = models.ManyToManyField(OrgStructure, verbose_name="组织机构",  blank=True,
                                 related_name='users')

    class Meta:
        verbose_name = '用户表'
        verbose_name_plural = verbose_name


class OrgLabel(models.Model):
    """
    机构岗位标签
    """
    name = models.CharField(verbose_name='名称', max_length=20)
    label_id = models.IntegerField(blank=True, null=True)  # 钉钉中角色对应的的ID
    user = models.ManyToManyField(User, verbose_name="用户", blank=True)
    is_active = models.BooleanField(default=True, verbose_name="是否激活状态")

    class Meta:
        verbose_name = '机构岗位标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
